<script setup>
import { useOrderStore } from '@/stores'
import * as echarts from 'echarts'
import { onMounted, onUnmounted, useTemplateRef } from 'vue'

const echartRef = useTemplateRef('echartRef')
const orderStore = useOrderStore()
const timeList = orderStore.orderList.map(item => item.orderTime)
const priceList = orderStore.orderList.map(item => item.totalPrice)
let myChart

function debounce(fn, delay = 300) {
  let timer = null
  return function () {
    if (timer) clearTimeout(timer)
    timer = setTimeout(fn, delay)
  }
}

const handleResize = debounce(() => {
  myChart && myChart.resize()
}, 300)

onMounted(() => {
  const chartDom = echartRef.value
  myChart = echarts.init(chartDom)
  window.addEventListener('resize', handleResize)

  const option = {
    tooltip: {
      trigger: 'item'
    },
    xAxis: {
      type: 'category',
      data: timeList
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '销售额',
        data: priceList,
        type: 'bar'
      }
    ]
  }

  option && myChart.setOption(option)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  myChart && myChart.dispose()
  console.log('销毁ECharts')
})
</script>

<template>
  <div class="order-statistics">
    <h2>订单统计</h2>
    <div ref="echartRef" class="echart"></div>
  </div>
</template>

<style scoped lang="scss">
.order-statistics {
  width: 100%;
  // height: 100%;
  height: calc(100% - 60px);

  h2 {
    margin-bottom: 40px;
  }

  .echart {
    width: 100%;
    height: 100%;
  }
}
</style>
